const express = require("express");
const router = express.Router();
const passport = require("passport");

const Profile = require("../../models/Profile");

// Middleware for authentication
const auth = passport.authenticate("jwt", { session: false });

// @route  GET api/profiles/test
// @desc   返回的请求的json数据
// @access public
router.get("/test", async (req, res) => {
  res.json({ msg: "profile works" });
});

// @route  POST api/profiles/add
// @desc   创建信息接口
// @access Private
router.post("/add", auth, async (req, res) => {
  try {
    const profile = await Profile.create(req.body);
    res.json(profile);
  } catch (err) {
    res.status(400).json(err);
  }
});

// @route  GET api/profiles
// @desc   获取所有信息
// @access Private
router.get("/", auth, async (req, res) => {
  try {
    const profiles = await Profile.find();
    res.json(profiles.length ? profiles : "没有任何内容");
  } catch (err) {
    res.status(400).json(err);
  }
});

// @route  GET api/profiles/:id
// @desc   获取单个信息
// @access Private
router.get("/:id", auth, async (req, res) => {
  try {
    const profile = await Profile.findById(req.params.id);
    res.json(profile ? profile : "没有任何内容");
  } catch (err) {
    res.status(404).json(err);
  }
});

// @route  POST api/profiles/edit/:id
// @desc   编辑信息接口
// @access Private
router.post("/edit/:id", auth, async (req, res) => {
  try {
    const profile = await Profile.findByIdAndUpdate(req.params.id, req.body, {
      new: true,
    });
    res.json(profile);
  } catch (err) {
    res.status(400).json(err);
  }
});

// @route  DELETE api/profiles/delete/:id
// @desc   删除信息接口
// @access Private
router.delete("/delete/:id", auth, async (req, res) => {
  try {
    const profile = await Profile.findByIdAndRemove(req.params.id);
    res.json(profile);
  } catch (err) {
    res.status(404).json("删除失败!");
  }
});

module.exports = router;
